#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <tiff.h>
#include <tiffio.h>
#include <tiffconf.h>
#include <tif_config.h>
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>

#include "defines.h"
#include "tiffoperations.h"

using namespace std;
using namespace cv;

//this routine converts a tiff image directory to an OpenCV mat type
Mat tiffToOpenCvMat(TIFF* tif, int dir)
{
	unsigned int width=0, height=0;
	size_t npixels;
	uint32 *raster;
	Mat temp, image;
	
	TIFFSetDirectory(tif, dir);
	TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);           
	TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height); 
	//calculate how many pixels the image consist of and store it
	npixels=width*height;
	//allocate memory for our raster which will be used to create an OpenCV Mat variable
	raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32));
		
	if (raster != NULL)
	{
		//read the tif's directory to the raster
		if (TIFFReadRGBAImageOriented(tif, width, height, raster, ORIENTATION_TOPLEFT , 0))
		{
			//place the raster into the OpenCV Mat variable
			temp = Mat(height, width, CV_8UC4, raster, Mat::AUTO_STEP);
			//convert it to the correct colorscheme
			cvtColor(temp, image, CV_8U, 3);
		}
		//free the allocated memory
		_TIFFfree(raster);
	}
	//close the tif file, we won't need it anymore now!
	TIFFClose(tif);
	//return the image and move along.
	return image;
}
